package com.joe.dev.springlearn.springmybatis.util;

import com.joe.dev.springlearn.springmybatis.dao.UserMapper;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//@Component
public class JoeFactoryBean implements FactoryBean {

    private Class mapperInterface;

    public JoeFactoryBean(Class mapperInterface){
        this.mapperInterface = mapperInterface;
    }

    @Override
    public Object getObject() throws Exception {

        Object o = Proxy.newProxyInstance(JoeFactoryBean.class.getClassLoader(), new Class[]{mapperInterface},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (Object.class.equals(method.getDeclaringClass())) {
                            return method.invoke(this, args);
                        }

                        return null;
                    }
                });

        return o;
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }
}
